package ru.xpparty.scanner;

import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;

/**
 * Implementation of parsing command line arguments to
 * the request object to scanner.
 * 
 * @author xp.party
 *
 */
public class ParserImpl implements Parser {

	private static final String PORT_ARG = "p";
	private static final String HOST_ARG = "h";
	private CommandLineParser commandLineParser;
	private CommandLine parseResult;	
	private Options options; 
	
	/**
	 * Constructor of parser with CommandLineParser argument
	 * 
	 * @param parser CommandLineParser
	 */
	public ParserImpl(CommandLineParser parser) {
		this.commandLineParser = parser;
		options = new Options();
		options.addOption(PORT_ARG, true, "Port number to scan");
		options.addOption(HOST_ARG, true, "Port number to scan");
	}
	
	
	
	/**
	 * Performs parsing command line arguments.
	 */
	@Override
	public Request parse(String[] args) {
		try {
			return tryParse(args);
		} catch (ParseException e) {
			throw new RuntimeException(e);
		}
	}
	
	/**
	 * Tries to parse command line arguments
	 * 
	 * @param args command line arguments
	 * @return parsed request to scanner
	 * @throws ParseException if syntax was incorrect
	 */
	private Request tryParse(String[] args) throws ParseException {		
		parseResult = commandLineParser.parse(options, args);
		return new Request(host(), port());
	}

	private String host() {
		return parseResult.getOptionValue(HOST_ARG);
	}


	private Integer port() {
		return Integer.valueOf(parseResult.getOptionValue(PORT_ARG));
	}
}
